package com.example.modelfunction.shrio;

import com.example.modelfunction.shrio.jwt.JWTToken;
import com.example.modelfunction.shrio.jwt.Jwt;
import com.example.modelfunction.shrio.usermanager.mode.Role;
import com.example.modelfunction.shrio.usermanager.mode.User;
import com.example.modelfunction.shrio.usermanager.repository.RoleRepository;
import com.example.modelfunction.shrio.usermanager.repository.UserRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;


    /**
     * 获取身份验证信息
     * Shiro中，最终是通过 Realm 来获取应用程序中的用户、角色及权限信息的。
     *
     * @param authenticationToken 用户身份信息 token
     * @return 返回封装了用户信息的 AuthenticationInfo 实例
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("————身份认证方法————");
        CredentialsMatcher mather = getCredentialsMatcher();
        User user = null;
        String pwd = null;
        if (authenticationToken instanceof JWTToken) {
            JWTToken token = (JWTToken) authenticationToken;
            Jwt jwt = new Jwt((String) token.getPrincipal());
            Long key = jwt.parseTokenString();
            if (key != null) {
                user = userRepository.getOne(key);
                if (null == user) {
                    throw new AccountException("用户名不正确");
                }
                if (!jwt.validateToken(user))
                    throw new AccountException("用户信息无效");
            } else
                throw new AccountException("token 验证错误");
            token.setUsername(user.getAccount());
            if (mather instanceof RetryLimitHashedCredentialsMatcher) {
                RetryLimitHashedCredentialsMatcher remather = (RetryLimitHashedCredentialsMatcher) mather;
                pwd = remather.getEncodePwd(user.getPwdSalt(), user.getPwdSalt(), 1);
            }

        } else if (authenticationToken instanceof UsernamePasswordToken) {
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            // 从数据库获取对应用户名密码的用户
            user = userRepository.findByAccount(token.getUsername());
            if (user == null)
                user = userRepository.findByTel(token.getUsername());
            if (null == user) {
                throw new AccountException("用户名不正确");
            } else if (!user.isValidate()) {
                throw new AccountException("用户名被禁用");
            }
            pwd = user.getPwd();
        }

       /* else if (!user.getPwd().equals(EncryptUtil.shaEncode(password, (String) user.getPwdSalt()))) {
            throw new AccountException("密码不正确");
        }*/

        ByteSource salt = ByteSource.Util.bytes(user.getPwdSalt());
//        return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), pwd, salt,getName());
        return new SimpleAuthenticationInfo(user, pwd, salt, getName());
       /*  SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(token.getPrincipal(), password, getName());
        info.setCredentialsSalt(new MySimpleByteSource(user.getPwdSalt()));//
             return info;*/
    }

    /**
     * 获取授权信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("————权限认证————");
        String name = (String) principalCollection.getPrimaryPrincipal();
        User user = userRepository.findByAccount(name);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获得该用户角色
        Optional<Role> mrole = roleRepository.findById(user.getRoleId().longValue());
        Role role = mrole.get();
        Set<String> set = new HashSet<>();
        //需要将 role 封装到 Set 作为 info.setRoles() 的参数
        set.add(role.getName());
        //设置该用户拥有的角色
        info.setRoles(set);
        return info;
    }
}
